<template>
    <div class="CompontensViews">
        <addMask v-if="addMaskFlg" @CloseTables="addMaskFlg = false" @getctgCodeValue="getctgCodeValue"></addMask>
        <!-- tabs -->
        <div class="bs-tabs">
            <!-- <el-button :type="activeFlag == index ? 'primary' : ''" :class="activeFlag == index ? '' : 'other-btn'"
                size="mini" :disabled="!macNamebValue && index != 0 ? true : false" v-for="(value, index) in tabs_list"
                :key="index" @click="activeFlag = index" style="width: 15% !important;">
                {{ value.title }}
            </el-button> -->
            <el-button :type="activeFlag == index ? 'primary' : ''" size="mini"
                :disabled="!macNamebValue && index != 0 ? true : false" v-for="(value, index) in tabs_list" :key="index"
                @click="activeFlag = index"
                style="width: 15% !important;border-radius: 0;font-size: 14px;height: 26px;line-height: 0;">
                {{ value.title }}
            </el-button>

            <!-- -是否修改-{{ DataChange }}- -->
        </div>
        <div class="add">
            <div style="display: flex;" v-show="activeFlag === 1">
                <p class="pl15">グループ：</p>
                <el-select class="form-ipt" v-model="tab2SelectValue[0]"
                    @change="getDetialsStyleComBoxFn(tab2SelectValue[0])">
                    <el-option v-for="item in tab2_Select.grnList" :key="item.key" :label="item.label"
                        :value="item.key"></el-option>
                </el-select>
                <p class="pl15">小グループ：</p>
                <el-select class="form-ipt" v-model="tab2SelectValue[1]">
                    <el-option v-for="item in tab2_Select.smlList" :key="item.key" :label="item.label"
                        :value="item.key"></el-option>
                </el-select>
            </div>
            <span></span>
            <div v-show="activeFlag === 0 || activeFlag === 5" v-if="$hasEditPermission('/BHView')">
                <el-button type="default" size="small" @click="addFn">追加</el-button>
                <el-button type="default" size="small" @click="delFn"
                    :disabled="!macNamebValue ? true : false">削除</el-button>
            </div>
        </div>
        <!-- 内容 -->
        <div class="container">
            <!-- <div class="content-center"> -->
            <BasicCps v-show="activeFlag === 0" ref="tab1" :ctgCodeValue="ctgCodeValue" @DataChangeFn="DataChangeFn">
            </BasicCps>
            <DetailCps v-show="activeFlag === 1" ref="tab2" :tab2SelectValue="tab2SelectValue"
                @DataChangeFn="DataChangeFn"></DetailCps>
            <FluidPressureCps v-show="activeFlag === 2" ref="tab3" @DataChangeFn="DataChangeFn"></FluidPressureCps>
            <DrawingCps v-show="activeFlag === 3" ref="tab4" @DataChangeFn="DataChangeFn"></DrawingCps>
            <PictureAssociationCps v-show="activeFlag === 4" ref="tab5" @DataChangeFn="DataChangeFn">
            </PictureAssociationCps>
            <PDFCps v-show="activeFlag === 5" ref="tab6" @isGetAgain="isGetAgain" @DataChangeFn="DataChangeFn"></PDFCps>
            <!-- </div> -->
            <div class="right-container-view">
                <RightTabelCps v-show="macType != 1" ref="tab7" @getctgCodeValue1="getctgCodeValue1"
                    :activeFlag="activeFlag" @retGetAllList="retGetAllList"></RightTabelCps>
            </div>
            <div class="footer" v-if="$hasEditPermission('/BHView')">
                <el-button @click="retGetAllList" :disabled="!macNamebValue ? true : false">Cancel</el-button>
                <el-button class="okBTn" type="primary" @click="saveData(true)"
                    :disabled="!macNamebValue ? true : false">編集内容を保存</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import BasicCps from "./BSDetailConmpontents/BasicCps.vue";
import DetailCps from "./BSDetailConmpontents/DetailCps.vue";
import FluidPressureCps from "./BSDetailConmpontents/FluidPressureCps.vue";
import DrawingCps from "./BSDetailConmpontents/DrawingCps.vue";
import PictureAssociationCps from "./BSDetailConmpontents/PictureAssociationCps.vue";
import PDFCps from "./BSDetailConmpontents/PDFCps.vue";
import addMask from "./BSDetailConmpontents/addMask.vue";
import RightTabelCps from "./BSDetailConmpontents/RightTabelCps.vue";
import { getLocalStorage } from "@/utils/storage";
import {
    getDetialsStyleComBox, addBasicStyleTipsMsg, addBasicStyle,
    delBasicStyle, delBasicStyleTipsMsg, addBasicStyleVerify, UpdBasicStyle,
    addLineNo, UpdBookRelaVerify
} from "@/api/api";
import eventBus from "@/eventBus/bus";
import { showLoading, hideLoading } from "@/utils/loading";
import _ from 'lodash-es';
export default {
    name: "BasicStyleCompontens",
    props: ["activeName"],
    data() {
        return {
            tabs_list: [
                {
                    title: this.$t("message.BSCps.tabs.label_1"),
                },
                {
                    title: this.$t("message.BSCps.tabs.label_2"),
                },
                {
                    title: this.$t("message.BSCps.tabs.label_3"),
                },
                {
                    title: this.$t("message.BSCps.tabs.label_4"),
                },
                {
                    title: this.$t("message.BSCps.tabs.label_5"),
                },
                {
                    title: this.$t("message.BSCps.tabs.label_6"),
                },
            ],
            activeFlag: 0,
            tab2_Select: [],
            tab2SelectValue: [0, -999],
            addMaskFlg: false,
            ctgCodeValue: '',
            OperType: 2,

            // 解决6的没数据错位情况
            isGetSixData: false,

            //  数据是否修改过
            DataChange: false,
            isConfirming: false,

            macTypeChange: false,
        };
    },
    components: {
        BasicCps,
        DetailCps,
        FluidPressureCps,
        DrawingCps,
        PictureAssociationCps,
        PDFCps,
        RightTabelCps,
        addMask
    },
    watch: {
        activeFlag: {
            deep: true,
            handler: function (newV, oldV) {
                console.log(newV);
                this.$store.state.baseTab5Flg = newV;
                if (newV == 1) {
                    // this.$refs.tab2.initFn();
                }
                if (newV == 1) {
                    this.$refs.tab2.$refs.singleTable.refreshColumn();
                }
                if (newV == 4) {
                    this.$refs.tab5.setTable();
                }
                if (newV == 5) {
                    this.$refs.tab6.$refs.singleTable.refreshColumn();
                }

            },
        },
        macNamebValue: {
            deep: true,
            handler: function (newV, oldV) {
                // 机器切换初始是保存编辑状态
                if (!newV) {
                    this.activeFlag = 0;
                }
                this.OperType = 2;
                this.getDetialsStyleComBoxFn(0);


                this.tab2SelectValue[0] = this.tab2_Select.grnList[0].key;
                this.tab2SelectValue[1] = this.tab2_Select.smlList[0].key;
            },
        },
        '$store.state.macType': {
            deep: true,
            handler: function (newV, oldV) {
                this.macTypeChange = true;
            },
        },
        // '$store.state.pltCode': {
        //     deep: true,
        //     handler: function (newV, oldV) {
        //         showLoading();
        //         setTimeout(() => {
        //             this.retGetAllList();
        //             hideLoading();
        //         }, 1000);
        //     },
        // }
    },
    computed: {
        macNamebValue() {
            return this.$store.state.macNameb;
        },
        macType() {
            return this.$store.state.macType;
        },
    },
    methods: {
        DataChangeFn(e) {
            this.DataChange = e;
        },
        isGetAgain(e) {
            console.log(e);
            this.isGetSixData = e;
        },
        // 数据保存
        async saveData(isSaveBtn) {
            // if (this.isConfirming) {
            //     return
            // }
            this.isConfirming = true;

            let res = await addBasicStyleTipsMsg();
            this.$confirm(res.data.data, '', {
                confirmButtonText: 'OK',
                cancelButtonText: 'Cancel',
                type: 'warning'
            }).then(() => {

                this.saveFn(isSaveBtn);

            }).catch(() => {
                // if (isRefresh) {
                //     this.$store.state.isCurrentFn();
                //     this.$store.commit("reSetIsCurrent");
                //     return
                // }

                if (isSaveBtn) {
                    return
                }
                this.$store.state.isCurrentFn();
                this.$store.commit("reSetIsCurrent");
            });
        },
        async saveFn(isSaveBtn) {
            // let tempMacNumb = this.$refs.tab1.basicStyleData.macNumb;
            // 图画关联验证

            let D = {
                DataList: this.$refs.tab5.prposTabelData,
                dmgCode: this.$store.state.macCode,
                Account: getLocalStorage('userName'),
            }
            let R = await UpdBookRelaVerify(D);
            if (!R || R.data.code == 452) {
                //  导航条误
                eventBus.$emit('isNavChangeErrorFn');
                //  搜索框索引误
                eventBus.$emit('backParamsForLeftView');
                return
            }

            let dataJson = {
                dmgCode: this.$store.state.macCode,
                OperType: this.OperType,//	是	int	当前编辑状态 0=没有状态 1=新增 2=编辑
                MacType: this.$store.state.macType,//	是	int	设备类型 1=机器 2=配管
                Account: getLocalStorage('userName'),//	是	string	登录账号
                PltCode: this.$store.state.pltCode,//	是	int	装置Code
                BasicStyleInfo: this.$refs.tab1.basicStyleData,//	是	T	基本仕様数据
                FluidTabDataInfo: this.$refs.tab3.allData,//	是	T	流体/圧力/温度数据
                PartsStyleInfo: this.$refs.tab6.prposTabelData,//	是	List<T>	部品仕样数据
                DetialsStyleInfo: this.$refs.tab2.prposTabelData,//	是	List<T>	详细仕样数据
                BookInfo: this.$refs.tab5.prposTabelData,//	图画关联
                DrawInfo: this.$refs.tab4.prposTabelData,
                LineNoInfo: this.$refs.tab7.prposTabelData, //连接
            }
            let res = await UpdBasicStyle(dataJson);
            hideLoading();
            if (!res || res.data.code == 452 || res.data.code != 0) {
                //  this.$emit('chenOldParams');
                //  导航条误
                eventBus.$emit('isNavChangeErrorFn');
                //  搜索框索引误
                eventBus.$emit('backParamsForLeftView');
                return
            }
            this.$message({
                type: 'success',
                message: res.data.msg
            });
            // eventBus.$emit('reGetLeftList', this.$refs.tab1.basicStyleData.macNumb);
            /**
             *  保存逻辑
             *  1. 保存成功后，执行原有逻辑
             *  2. 保存成功后，保存按钮return
             *  3. 保存成功后，追加逻辑，执行追加函数，并return
             *  4. 保存成功后，this.$store.state.isCurrentFn()，执行this.$store.state.isCurrentFn()，并return
             */
            //  重新加载左侧的列表
            eventBus.$emit('reGetLeftList', this.$refs.tab1.basicStyleData.macNumb);
            this.$store.commit("changeMacNameb", this.$refs.tab1.basicStyleData.macNumb);
            this.$store.commit("changeMacName", this.$refs.tab1.basicStyleData.macName);

            this.retGetAllList();

            if (isSaveBtn) {
                return
            }
            if (this.macTypeChange) {
                this.macTypeChange = false;
                this.$store.state.isCurrentFn()
                this.$store.commit("reSetIsCurrent");
                return
            }
            eventBus.$emit('reGetLeftList', this.$store.state.leftRowName);
            this.$store.state.isCurrentFn()
            this.$store.commit("reSetIsCurrent");
        },
        // 获取新增初始
        async getctgCodeValue(value) {
            console.log(333);
            let dataJson = {
                PltCode: this.$store.state.pltCode,
                MacType: this.$store.state.macType,//	是	int	1=机器 2=配管
                MacNumb: "New",//	是	string	设备编号 例：100-E001
            }
            let res = await addBasicStyleVerify(dataJson);
            if (!res || res.data.code == 452) {
                return
            }
            showLoading();

            let dataJson1 = {
                RType: 0, //RType（int） 0=设备  1=LineNo   你传1
                OperType: 1,//	是	int	当前编辑状态 0=没有状态 1=新增 2=编辑
                MacType: this.$store.state.macType,//	是	int	设备类型 1=机器 2=配管
                account: getLocalStorage('userName'),//	是	string	登录账号
                PltCode: this.$store.state.pltCode,//	是	int	装置Code
                BasicStyleInfo: {
                    ctgCode: value,
                    MacNumb: this.$refs.tab1.basicStyleData.macNumb,
                    DmgCode: this.$refs.tab1.basicStyleData.dmgCode
                },//	是	T	基本仕様数据
                FluidTabDataInfo: {},//	是	T	流体/圧力/温度数据
                PartsStyleInfo: [],//	是	List<T>	部品仕样数据
                DetialsStyleInfo: [],//	是	List<T>	详细仕样数据

                LineNoInfo: [], //连接
            }

            let res1 = await addBasicStyle(dataJson1);

            hideLoading();
            if (!res1) {
                return
            }
            this.$message({
                type: 'success',
                message: res1.data.msg
            });

            setTimeout(() => {
                this.$store.commit("changeMacNameb", this.$refs.tab1.basicStyleData.macNumb);
                this.$store.commit("changeMacName", this.$refs.tab1.basicStyleData.macName);
                eventBus.$emit('reGetLeftList', "New");
            }, 300);
        },

        // 获取新增初始
        async getctgCodeValue1(value) {
            // console.log(333);
            // let dataJson = {
            //     PltCode: this.$store.state.pltCode,
            //     MacType: this.$store.state.macType,//	是	int	1=机器 2=配管
            //     MacNumb: "New",//	是	string	设备编号 例：100-E001
            // }
            // let res = await addBasicStyleVerify(dataJson);
            // if (!res) {
            //     return
            // }
            this.activeFlag = 0;
            showLoading();

            let dataJson1 = {
                RType: 1, //RType（int） 0=设备  1=LineNo   你传1
                OperType: 1,//	是	int	当前编辑状态 0=没有状态 1=新增 2=编辑
                MacType: this.$store.state.macType,//	是	int	设备类型 1=机器 2=配管
                account: getLocalStorage('userName'),//	是	string	登录账号
                PltCode: this.$store.state.pltCode,//	是	int	装置Code
                BasicStyleInfo: {
                    ctgCode: value,
                    MacNumb: this.$refs.tab1.basicStyleData.macNumb,
                    DmgCode: this.$refs.tab1.basicStyleData.dmgCode
                },//	是	T	基本仕様数据
                FluidTabDataInfo: {},//	是	T	流体/圧力/温度数据
                PartsStyleInfo: [],//	是	List<T>	部品仕样数据
                DetialsStyleInfo: [],//	是	List<T>	详细仕样数据

                LineNoInfo: [], //连接
            }

            let res1 = await addLineNo(dataJson1);

            hideLoading();
            if (!res1) {
                return
            }
            this.$message({
                type: 'success',
                message: res1.data.msg
            });
            setTimeout(() => {
                this.$store.commit("changeMacNameb", this.$refs.tab1.basicStyleData.macNumb);
                this.$store.commit("changeMacName", 'New');
                // eventBus.$emit('reGetLeftList', "New");
            }, 300);
        },
        async delFn() {
            if (this.activeFlag == 5) {
                this.$refs.tab6.tableDataDel();
            }
            if (this.activeFlag == 0) {
                let dataJson = {
                    MacType: this.$store.state.macType,//	是	int	1=机器 2=配管
                    MacNumb: this.$store.state.macNameb,//	是	string	设备编号 例：100-E001
                }
                let res = await delBasicStyleTipsMsg(dataJson);
                this.$confirm(res.data.msg, '', {
                    confirmButtonText: 'OK',
                    cancelButtonText: 'Cancel',
                    type: 'warning'
                }).then(async () => {
                    let dataJson = {
                        OperType: 0,
                        DmgCode: this.$store.state.macCode,
                    }
                    let res = await delBasicStyle(dataJson);
                    if (res.data.code != 0) {
                        this.$message({
                            type: 'warning',
                            message: res.data.msg
                        });
                        return
                    }
                    // this.$refs.tab1.clearData();
                    this.$store.state.macNameb = '';
                    this.$message({
                        type: 'success',
                        message: res.data.msg
                    });
                    eventBus.$emit('reGetLeftList');
                }).catch(() => {
                });
            }
        },
        addFn() {
            if (this.activeFlag == 5) {
                this.$refs.tab6.tableDataAdd();
                return
            }
            eventBus.$emit('getBasicStyleCompontensCurrent_EventBus');	//	基本仕样

            let Fn = () => {
                if (this.activeFlag == 0) {
                    this.addMaskFlg = true;
                }

            }
            if (this.$store.state.isCurrentNext) {
                Fn();
            } else {
                /**
                  * 4-1。   记录原来该运行的函数。
                  * 4-2。   执行保存弹出框操作。   
                  */
                this.$store.commit("changeIsCurrentFn", Fn);

                eventBus.$emit('EventBusBasicStyleCompontensSaveFn');	//	基本仕样
            }

        },
        // init
        // 获取2的下拉框属性
        async getDetialsStyleComBoxFn(GrpCode) {
            let dataJson = {
                CtgCode: this.$store.state.ctgRowCode == "" ? 0 : this.$store.state.ctgRowCode,
                GrpCode
            };
            let res = await getDetialsStyleComBox(dataJson);
            console.log(res);
            this.tab2_Select = res.data.data;
        },
        initFn() {
            this.getDetialsStyleComBoxFn(0);
        },
        retGetAllList() {

            this.$refs.tab1.initFn();
            this.$refs.tab2.initFn();
            this.$refs.tab3.initFn();
            this.$refs.tab5.initFn();
            this.$refs.tab4.initFn();
            this.$refs.tab6.initFn();
            this.$refs.tab7.initFn();
        }
    },



    created() {
    },
    mounted() {
        this.initFn()
        this.$store.state.baseTab5Flg = 0;

        //  监听通知，是否有数据变更
        eventBus.$on('getBasicStyleCompontensCurrent_EventBus', () => {
            console.log('getBasicStyleCompontensCurrent_EventBus', '基本仕样');

            // 获取当前数据是否更改。
            this.$store.commit("changeIsCurrentNext", !this.DataChange);
        });

        //  接受通知唤起保存弹框
        eventBus.$on('EventBusBasicStyleCompontensSaveFn', () => {
            this.saveData();
        });
    },
    beforeDestroy() {
        eventBus.$off('getBasicStyleCompontensCurrent_EventBus');
        eventBus.$off('EventBusBasicStyleCompontensSaveFn');
    },
    destroyed() { },
};
</script>
<style lang="scss" scoped>
.CompontensViews {
    width: 100%;
    height: 100%;
    position: relative;

    .add {
        min-height: 70px;
        width: 72%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 26px 0 12px 0;

        button {
            // background-color: #fff;
            width: 82px;
            height: 32px;
            line-height: 0;
            font-size: 14px;
        }

        .pl15 {
            padding-left: 15px;
        }

        .form-ipt {
            width: 200px;
            height: 24px;

            ::v-deep .el-input__inner {
                height: 24px;
                background: #fff;
            }

            ::v-deep .el-input__icon {
                line-height: 24px;
            }
        }
    }
}

.bs-tabs {
    margin-top: 16px;
    // width: 100%;
    width: 72%;
    height: 32px;
    display: flex;
    align-items: center;

    // justify-content: flex-start;
    // background-color: #106ebe;
    .el-button+.el-button {
        margin-left: 0px;
        min-width: 15%;
        width: 15%;
        border-radius: 0 !important;
    }

    .tabs-btn {
        width: 15%;
        min-width: 15%;

        height: 32px;
        flex-grow: 1;
        border: 1px solid #d3d3d3;
        border-right: 0 none;
    }

    // .tabs-btn:nth-child(1) {
    //     border-radius: 0 !important;
    // }

    // .tabs-btn:last-child {
    //     border-right: 1px solid #d3d3d3;
    //     border-radius: 0 4px 4px 0;
    // }

    // .active-btn {
    //     background: #106ebe;
    //     color: #fff;
    // }

    .other-btn {
        background-color: #FFF;
        border-radius: 0 !important;

    }
}

.container {
    position: relative;
    // margin-top: 38px;
    width: 100%;
    height: calc(100% - 120px);
    // overflow-y: auto;
    display: flex;
    justify-content: space-between;
}

.content-center {
    width: 72%;
    max-height: calc(100% - 51px);
    // overflow: hidden;
    overflow-y: auto;
    // overflow-x: auto;
    border: 1px solid #c3c3c3;
}

.right-container-view {
    height: 100%;
    width: calc(38% - 15px);
    margin-left: 20px;
}

.footer {
    position: absolute;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    bottom: 5px;
    left: 0;
    transform: translateY(3px);

    button {
        width: 123px;
        padding: 0 15px;
        height: 32px;
        // background: #ffffff;
        // border: 1px solid #d9d9d9;
        text-align: center;
        line-height: 32px;
        margin-right: 16px;
        border-radius: 0;
    }

    .okBTn {
        // background: #106ebe;
        // color: #fff;
    }
}

.elx-table--empty-content {
    transform: translateY(30px);
}
</style>
